import cn.hutool.core.date.DateUtil;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.wdh.dbutil.MongoUtil;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;

public class MongoTest2 {

    private  MongoCollection coll;

    @BeforeEach
    public void init(){
        coll = MongoUtil.getCollection("db_wdh", "hello100");
    }

    @Test
    public void dateTest()throws Exception{
        Document doc1 = new Document();
        doc1.put("name","张三");
        doc1.put("createDate",new Date());  //差了8小时

        Document doc2 = new Document();
        doc2.put("name","李四");
        doc2.put("createDate",LocalDateTime.now()); //时间正确，北京时间

        coll.insertMany(Arrays.asList(doc1,doc2));
    }

    /**
     * // 1
     * {
     *     "_id": ObjectId("6608ba9de4d2f636cb4c8d0c"),
     *     "name": "张三",
     *     "createDate": ISODate("2024-03-31T01:21:33.09Z")
     * }
     *
     * // 2
     * {
     *     "_id": ObjectId("6608ba9de4d2f636cb4c8d0d"),
     *     "name": "李四",
     *     "createDate": ISODate("2024-03-31T09:21:33.097Z")
     * }
     * */
    @Test
    public void dateQuery1(){
        /**查询不出来，因为到了mongo里，时间又少了8小时*/
        Date date = DateUtil.parse("2024-03-31 01:22:33", "yyyy-MM-dd HH:mm:ss").toJdkDate();
        Bson condition = Filters.lte("createDate", date);
        long count = coll.countDocuments(condition);
        System.out.println("-------------------");
        System.out.println(count);
    }

    /**
     * 数据参考dateQuery1
     *  时间查询在程序里使用LocalDateTime,TTL则需要使用Date
     * */
    @Test
    public void dateQuery2(){
        /**可以查询出来*/
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse("2024-03-31 01:22:33", dateTimeFormatter);
        Bson condition = Filters.lte("createDate", localDateTime);
        long count = coll.countDocuments(condition);
        System.out.println("-------------------");
        System.out.println(count);
    }

}
